import "../lib/jquery.js";
import axios from "../lib/axios.js";

$(function () {
  const authorization = localStorage.getItem("authorization");
  const user = JSON.parse(localStorage.getItem("user"));

  if (authorization && user) {
    fetchUserInfo(user.id, authorization);
  }

  // 点击个人资料按钮事件
  $("button.self").click(function () {
    location.href = "self.html";
  });

  // 点击注销按钮事件
  $("button.logout").click(function () {
    handleLogout();
  });

  // 获取用户信息的函数
  function fetchUserInfo(userId, token) {
    axios
      .get("http://localhost:9000/users/info", {
        params: { id: userId },
        headers: { authorization: token },
      })
      .then(({ data }) => {
        if (data.code === 1) {
          displayUserInfo(data.user.nickname);
        } else if (data.code === 401) {
          handleUnauthorizedAccess();
        }
      })
      .catch(error => {
        console.error("Error fetching user info:", error);
        alert("无法获取用户信息，请稍后再试。");
      });
  }

  // 显示用户信息的函数
  function displayUserInfo(nickname) {
    $("p.off").hide();
    $("p.on").show();
    $("span.nickname").text(nickname);
  }

  // 处理未授权访问的函数
  function handleUnauthorizedAccess() {
    localStorage.removeItem("authorization");
    localStorage.removeItem("user");
    alert("认证失败，请重新登录。");
    location.href = "login.html";
  }

  // 处理注销操作的函数
  function handleLogout() {
    const confirmed = window.confirm("确定要注销登陆？");

    if (confirmed) {
      alert("注销登陆成功");
      localStorage.removeItem("authorization");
      localStorage.removeItem("user");
      $("p.off").show();
      $("p.on").hide();
      location.href = "login.html";
    }
  }
});
